const jwt = require('jsonwebtoken')
// const secret = require('../config').jwt.secret
const { secret } = require('../config').jwt

const User = require('../model/User')
const bcrypt = require('bcryptjs')

class userController {
    static async userLogin(req, res) {
        const user = req.body
        if (user.user && user.pwd) {
            if (!user.user.trim() || !user.pwd.trim()) {
                return res.status(400).send({
                    code: 400,
                    msg: '账号或密码为空',
                })
            }
        } else return res.status(400).send({ code: 400, err: '参数错误' })

        try {
            const re = await User.findOne({ user: user.user })
            if (!re) return res.status(400).send({ code: 400, msg: '用户不存在' })

            // 异步密码比较
            bcrypt.compare(user.pwd, re.pwd).then(valid => {
                // if (!valid) return res.status(400).send({ code: 400, msg: '密码错误' })
                !valid && res.status(400).send({ code: 400, msg: '密码错误' })

                const token = jwt.sign({ user }, secret, { expiresIn: '2h' })
                res.json({
                    code: 200,
                    token,
                    msg: '登录成功',
                })
            })
        } catch (error) {
            console.log(error)
            res.status(500).send({
                code: 500,
                err: '服务器错误',
            })
        }
    }

    static async userRegister(req, res) {
        const user = req.body
        if (user.user && user.pwd) {
            if (!user.user.trim() || !user.pwd.trim()) {
                return res.status(400).send({
                    code: 400,
                    msg: '账号或密码为空',
                })
            }
        } else return res.status(400).send({ code: 400, err: '参数错误' })

        try {
            const isHave = await User.findOne({ user: user.user })
            if (isHave) return res.status(400).send({ code: 400, msg: '用户已存在' })
            let re = await User.create(user)
            // delete user.pwd
            let { user } = re
            res.status(201).send({
                code: 201,
                data: user,
                msg: '注册成功',
            })
        } catch (error) {
            console.log(error)
            res.status(500).send({
                code: 500,
                err: '服务器错误',
            })
        }
    }
}

module.exports = userController
